package com.hyz.reggie.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hyz.reggie.common.RedisKeys;
import com.hyz.reggie.dto.DishDto;
import com.hyz.reggie.pojo.Dish;
import com.hyz.reggie.pojo.R;
import com.hyz.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService service;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R findDishByPage(Integer page, Integer pageSize, String name) {
        IPage<DishDto> iPage = service.findByPage(page, pageSize, name);
        return R.success(iPage);
    }

    @PostMapping
    public R addDish(@RequestBody DishDto dishDto) {
        service.saveDish(dishDto);
        Long categoryId = dishDto.getCategoryId();
        redisTemplate.delete(RedisKeys.DISH_ + categoryId);
        return R.success("添加成功~");
    }

    @PostMapping("/status/{status}")
    public R modifyStatus(Long[] ids, @PathVariable Integer status) {
        Arrays.stream(ids).forEach(id -> {
            Dish dish = service.getById(id);
            dish.setStatus(status);
            service.updateById(dish);
        });
        return R.success(status == 0 ? "停售成功~" : "起售成功~");
    }

    //删除菜品要检验该菜品是否和某个套餐绑定
    @DeleteMapping
    public R deleteById(Long[] ids) {
        service.deleteByIds(ids);
        return R.success("删除成功~");
    }

    @GetMapping("/{id}")
    public R modifyDish(@PathVariable Long id) {
        DishDto dto = service.modifyDishById(id);

        return dto != null ? R.success(dto) : R.error("服务器繁忙，请稍后重试~");
    }

    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        service.updateDishDto(dishDto);
        Long categoryId = dishDto.getCategoryId();
        redisTemplate.delete(RedisKeys.DISH_ + categoryId);
        return R.success("修改成功~");
    }

    @GetMapping("/list")
    public R list(Long categoryId, Integer status) {
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(RedisKeys.DISH_ + categoryId);
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }
        List<DishDto> list = service.getList(categoryId, status);
        redisTemplate.opsForValue().set(RedisKeys.DISH_ + categoryId, list);
        return R.success(list);
    }
}
